package com.hitfm.iplay.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.hitfm.iplay.MusicInfoController;
import com.hitfm.iplay.MusicPlayerApp;
import com.hitfm.iplay.MusicPlayerService;
import com.hitfm.iplay.R;

public class MysongActivity extends Activity {
	private MusicPlayerService mMusicPlayerService = null;
	private MusicInfoController mMusicInfoController = null;
	private Cursor mCursor = null;

	private static final String TAG = "iplay";

	private TextView localsong;
	private TextView recentplay;
	private TextView playlist;
	private TextView favorite;
	protected Intent intent;
	private ImageView backto_localsong;
	private TextView allsong;
	private TextView folder;
	private TextView singer;
	private TextView random_play;
	private ListView list_localsongAll;
	private MusicListAdapter adapter;
	private LinearLayout layout_mySong;
	private LinearLayout layout_localSongAll;

	private ServiceConnection mPlaybackConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder service) {
			mMusicPlayerService = ((MusicPlayerService.LocalBinder) service)
					.getService();
		}

		public void onServiceDisconnected(ComponentName className) {
			mMusicPlayerService = null;
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mysong);

		findMySongViews();
		setMySongListeners();
	}

	protected BroadcastReceiver mPlayerEvtReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(MusicPlayerService.PLAYER_PREPARE_END)) {
				// will begin to play
				playing_id.setText(clickItemNum + ". " + clickItemSinger + "--"
						+ clickItemName);
				playing_id.setVisibility(View.VISIBLE);
			} else if (action.equals(MusicPlayerService.PLAY_COMPLETED)) {
				playing_id.setVisibility(View.INVISIBLE);
			}
		}
	};
	protected int clickItemNum = 0;
	private TextView playing_id;
	protected String clickItemName;
	protected String clickItemSinger;
	private MusicPlayerApp musicPlayerApp;
	protected boolean isMysongLayout = true;

	private void findMySongViews() {
		// 我的歌曲
		layout_mySong = (LinearLayout) findViewById(R.id.layout_mysong);
		localsong = (TextView) findViewById(R.id.local_song);
		recentplay = (TextView) findViewById(R.id.recent_play);
		playlist = (TextView) findViewById(R.id.playlist);
		favorite = (TextView) findViewById(R.id.favorite);
		// 本地歌曲
		layout_localSongAll = (LinearLayout) findViewById(R.id.layout_localsong_all);
		backto_localsong = (ImageView) findViewById(R.id.backto_localsong);
		allsong = (TextView) findViewById(R.id.allsong);
		folder = (TextView) findViewById(R.id.folder);
		singer = (TextView) findViewById(R.id.singer);
		random_play = (TextView) findViewById(R.id.random_play);
		playing_id = (TextView) findViewById(R.id.playing_id);
	}

	private void setMySongListeners() {
		// 我的歌曲
		localsong.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				initService();
				showAllSongList();
				isMysongLayout = false;
				layout_localSongAll.setVisibility(View.VISIBLE);
				layout_mySong.setVisibility(View.INVISIBLE);
			}
		});
		// 本地歌曲
		backto_localsong.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				backToMysong();
			}
		});
		allsong.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				setButtonColor(R.color.gray, R.color.lightgray,
						R.color.lightgray);
			}
		});
		folder.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				setButtonColor(R.color.lightgray, R.color.gray,
						R.color.lightgray);
			}
		});
		singer.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				setButtonColor(R.color.lightgray, R.color.lightgray,
						R.color.gray);
			}
		});
	}

	protected void setButtonColor(int allcolor, int foldercolor, int singercolor) {
		// allsong.setBackgroundColor(allcolor);
		// folder.setBackgroundColor(foldercolor);
		// singer.setBackgroundColor(singercolor);
	}

	protected void backToMysong() {
		layout_localSongAll.setVisibility(View.INVISIBLE);
		layout_mySong.setVisibility(View.VISIBLE);
	}

	protected void initService() {
		musicPlayerApp = (MusicPlayerApp) getApplication();
		mMusicInfoController = musicPlayerApp.getMusicInfoController();

		startService(new Intent(this, MusicPlayerService.class));
		getApplicationContext().bindService(
				new Intent(this, MusicPlayerService.class),
				mPlaybackConnection, Context.BIND_AUTO_CREATE);

		IntentFilter filter = new IntentFilter();
		filter.addAction(MusicPlayerService.PLAYER_PREPARE_END);
		filter.addAction(MusicPlayerService.PLAY_COMPLETED);
		filter.addAction(MusicPlayerService.PLAY_PAUSE);
		filter.addAction(MusicPlayerService.PLAY_CONTINUE);
		filter.addAction(MusicPlayerService.ERROR);
		registerReceiver(mPlayerEvtReceiver, filter);
	}

	protected void showAllSongList() {
		list_localsongAll = (ListView) findViewById(R.id.list_localsong_all);
		if (null == musicPlayerApp.getCursor()) {
			musicPlayerApp.initCursor();
		}
		mCursor = musicPlayerApp.getCursor();
		if (null == mCursor || mCursor.getCount() == 0) {
			playing_id.setText(R.string.nosong);
			playing_id.setVisibility(View.VISIBLE);
			return;
		}
		mCursor.moveToFirst();
		adapter = new MusicListAdapter(this, R.layout.list_allsong_item,
				mCursor, new String[] {}, new int[] {});
		list_localsongAll.setAdapter(adapter);
		list_localsongAll.setDivider(null);
		setListListner();
		setTitle();
	}

	private void setTitle() {
		if (null != mMusicPlayerService && mMusicPlayerService.isPlaying()) {
			mCursor.moveToPosition(mMusicPlayerService.getId());
			playing_id.setText((clickItemNum + 1) + ". " + clickItemSinger
					+ "--" + clickItemName);
			playing_id.setVisibility(View.VISIBLE);
		}
	}

	private void setListListner() {
		list_localsongAll.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
			}
		});
		list_localsongAll.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View clicked,
					int position, long arg3) {
				if (mCursor == null || mCursor.getCount() == 0) {
					return;
				}
				if (!mCursor.moveToPosition(position)) {
					Toast.makeText(MysongActivity.this, R.string.nosong,
							Toast.LENGTH_SHORT).show();
					return;
				}
				String url = mCursor.getString(mCursor
						.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));

				// TextView num = (TextView) clicked
				// .findViewById(R.id.list_allsong_item_num);
				clickItemNum = position;
				TextView song_name = (TextView) clicked
						.findViewById(R.id.list_allsong_item_song_name);
				clickItemName = song_name.getText().toString();
				TextView singer = (TextView) clicked
						.findViewById(R.id.list_allsong_item_singer);
				clickItemSinger = singer.getText().toString();
				mMusicPlayerService.setId(clickItemNum);
				if (mMusicPlayerService != null
						&& mMusicPlayerService.getMusicPath() == url) {
					mMusicPlayerService.pause();
				} else if (mMusicPlayerService != null) {
					mMusicPlayerService.stop();
					mMusicPlayerService.setMusicPath(url);
					mMusicPlayerService.start();
				} else {
					Toast.makeText(MysongActivity.this, "ERROR",
							Toast.LENGTH_SHORT).show();
				}
				adapter.notifyDataSetChanged();
			}
		});

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && !isMysongLayout) {
			backToMysong();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	protected void onRestart() {

		super.onRestart();
		if (null != adapter) {
			musicPlayerApp.initCursor();
			mCursor = musicPlayerApp.getCursor();
			adapter.notifyDataSetChanged();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// musicPlayerApp.closeCursor();
		// unbindService(mPlaybackConnection);
		stopService(new Intent(this, MusicPlayerService.class));
		// unregisterReceiver(mPlayerEvtReceiver);
	}

	class MusicListAdapter extends SimpleCursorAdapter {

		public MusicListAdapter(Context context, int layout, Cursor c,
				String[] from, int[] to) {
			super(context, layout, c, from, to);
			if (mCursor == null || mCursor.getCount() == 0) {
				return;
			}
		}

		public void bindView(View view, Context context, Cursor cursor) {
			super.bindView(view, context, cursor);
			view.setBackgroundColor((cursor.getPosition() % 2 == 0) ? Color.WHITE
					: 0xFFF5F5F5);
			TextView num = (TextView) view
					.findViewById(R.id.list_allsong_item_num);
			num.setText("" + (cursor.getPosition() + 1));
			TextView song_name = (TextView) view
					.findViewById(R.id.list_allsong_item_song_name);
			song_name.setText(cursor.getString(cursor
					.getColumnIndex(MediaStore.Audio.Media.TITLE)));
			TextView album = (TextView) view
					.findViewById(R.id.list_allsong_item_album);
			album.setText(cursor.getString(cursor
					.getColumnIndex(MediaStore.Audio.Media.ALBUM)));
			TextView singer = (TextView) view
					.findViewById(R.id.list_allsong_item_singer);
			singer.setText(cursor.getString(cursor
					.getColumnIndex(MediaStore.Audio.Media.ARTIST)));
			// ImageView playTagView = (ImageView) view
			// .findViewById(R.id.list_allsong_item_play_tag);
			// if (mMusicPlayerService!=null&&mMusicPlayerService.isPlaying()
			// && mMusicPlayerService.getId() == Integer
			// .parseInt((String) num.getText())) {
			// playTagView
			// .setVisibility(playTagView.getVisibility() == View.VISIBLE ?
			// View.INVISIBLE
			// : View.VISIBLE);
			// Log.e(TAG, ""+num);
			// }
		}
	}

}
